package com.boot.mall.product.config;

import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 我们自己配置的Redis缓存配置
 */

@EnableCaching  //开启缓存功能
@Configuration
public class MyCacheConfig {

    @Bean
    RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties){
        //链式调用config方法
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        //设置key的序列化器
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        //设置value的序列化器
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
        CacheProperties.Redis propertiesRedis = cacheProperties.getRedis();
        //将配置文件中其他的配置内容生效
        if (propertiesRedis.getTimeToLive() != null){
            //设置过期时间
            config = config.entryTtl(propertiesRedis.getTimeToLive());
        }
        if (!propertiesRedis.isCacheNullValues()){
            config = config.disableCachingNullValues();
        }
        if (!propertiesRedis.isUseKeyPrefix()){
            config = config.disableKeyPrefix();
        }
        return config;
    }

}
